import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import userService from '../services/userService';
import axios from 'axios';
import './FormStyles.css';

function AuthStatusTestPage() {
    const { currentUser, isAuthenticated } = useAuth();
    const [localStorageInfo, setLocalStorageInfo] = useState({});
    const [apiResponse, setApiResponse] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [tokenInfo, setTokenInfo] = useState(null);

    useEffect(() => {
        // 获取localStorage中的信息
        const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null;
        const token = localStorage.getItem('token');
        setLocalStorageInfo({
            user,
            token,
            tokenShort: token ? `${token.substring(0, 15)}...` : null
        });

        // 如果有token，解析它
        if (token) {
            try {
                const tokenParts = token.split('.');
                if (tokenParts.length === 3) {
                    const payload = JSON.parse(atob(tokenParts[1]));
                    setTokenInfo({
                        header: JSON.parse(atob(tokenParts[0])),
                        payload,
                        expiration: new Date(payload.exp * 1000).toLocaleString(),
                        isExpired: Date.now() > payload.exp * 1000
                    });
                }
            } catch (err) {
                setError(`解析Token出错: ${err.message}`);
            }
        }
    }, []);

    const testProfileAPI = async () => {
        setLoading(true);
        setError('');
        try {
            // 使用调试日志记录请求头
            console.log('开始测试/api/users/profile请求...');
            const token = localStorage.getItem('token');
            console.log('Token in localStorage:', token ? 'Present' : 'Not found');
            
            if (token) {
                console.log('Authorization header will be:', `Bearer ${token.substring(0, 15)}...`);
            }
            
            const response = await userService.getCurrentUserProfile();
            console.log('API请求成功:', response);
            setApiResponse(response.data);
        } catch (err) {
            console.error('API请求失败:', err);
            setError(`API请求失败: ${err.response ? `${err.response.status} - ${err.response.statusText}` : err.message}`);
        } finally {
            setLoading(false);
        }
    };

    const resetToken = () => {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.reload();
    };

    const generateNewTestRequest = async () => {
        setLoading(true);
        try {
            // 创建一个简单的测试请求，直接使用axios并手动设置认证头
            const token = localStorage.getItem('token');
            
            const response = await axios.get('http://localhost:8080/api/users/profile', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            
            console.log('直接Axios请求成功:', response);
            setApiResponse(response.data);
        } catch (err) {
            console.error('直接Axios请求失败:', err);
            setError(`直接Axios请求失败: ${err.response ? `${err.response.status} - ${err.response.statusText}` : err.message}`);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="form-container" style={{ maxWidth: '800px' }}>
            <h2>认证状态测试页面</h2>
            
            <div className="card">
                <h3>当前认证状态</h3>
                <p><strong>当前用户是否已登录:</strong> {isAuthenticated ? '是' : '否'}</p>
                {currentUser && (
                    <div>
                        <p><strong>用户名:</strong> {currentUser.username}</p>
                        <p><strong>邮箱:</strong> {currentUser.email}</p>
                        <p><strong>角色:</strong> {currentUser.roles?.join(', ') || '未知'}</p>
                    </div>
                )}
            </div>

            <div className="card">
                <h3>localStorage 存储信息</h3>
                {localStorageInfo.token ? (
                    <div>
                        <p><strong>Token 存在:</strong> 是</p>
                        <p><strong>Token 片段:</strong> {localStorageInfo.tokenShort}</p>
                    </div>
                ) : (
                    <p><strong>Token:</strong> 未找到</p>
                )}
                
                {localStorageInfo.user ? (
                    <div>
                        <p><strong>用户信息存在:</strong> 是</p>
                        <p><strong>用户名:</strong> {localStorageInfo.user.username}</p>
                        <p><strong>角色:</strong> {localStorageInfo.user.roles?.join(', ') || '未知'}</p>
                    </div>
                ) : (
                    <p><strong>用户信息:</strong> 未找到</p>
                )}
            </div>

            {tokenInfo && (
                <div className="card">
                    <h3>Token 解析</h3>
                    <p><strong>算法:</strong> {tokenInfo.header.alg}</p>
                    <p><strong>用户名:</strong> {tokenInfo.payload.sub}</p>
                    <p><strong>角色:</strong> {tokenInfo.payload.roles}</p>
                    <p><strong>过期时间:</strong> {tokenInfo.expiration}</p>
                    <p><strong>是否已过期:</strong> {tokenInfo.isExpired ? '是' : '否'}</p>
                    <pre style={{maxHeight: '200px', overflow: 'auto'}}>
                        {JSON.stringify(tokenInfo.payload, null, 2)}
                    </pre>
                </div>
            )}

            <div className="card">
                <h3>API 测试</h3>
                <button 
                    onClick={testProfileAPI} 
                    disabled={loading}
                    className="submit-button"
                >
                    {loading ? '请求中...' : '测试 /api/users/profile'}
                </button>
                
                <button 
                    onClick={generateNewTestRequest} 
                    disabled={loading}
                    className="submit-button"
                    style={{marginLeft: '10px'}}
                >
                    直接使用Axios测试
                </button>
                
                <button 
                    onClick={resetToken} 
                    className="submit-button"
                    style={{marginLeft: '10px', backgroundColor: '#dc3545'}}
                >
                    清除Token并刷新
                </button>

                {error && <p className="error-message">{error}</p>}
                
                {apiResponse && (
                    <div>
                        <h4>响应结果:</h4>
                        <pre style={{maxHeight: '300px', overflow: 'auto'}}>
                            {JSON.stringify(apiResponse, null, 2)}
                        </pre>
                    </div>
                )}
            </div>
            
            <style jsx>{`
                .card {
                    background-color: #f8f9fa;
                    border-radius: 5px;
                    padding: 15px;
                    margin-bottom: 20px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                }
                pre {
                    background-color: #f1f1f1;
                    padding: 10px;
                    border-radius: 4px;
                    white-space: pre-wrap;
                    word-break: break-all;
                }
            `}</style>
        </div>
    );
}

export default AuthStatusTestPage; 